//
//  TranslateView.swift
//  Encrypto VPN
//
//  Created by 周波 on 2024/7/4.
//

import SwiftUI

struct TranslateView: View {
    @State private var beforeSelectedLanguage = "English"
    @State private var afterSelectedLanguage = "Chinese"
    @Environment(\.presentationMode) var presentationMode
    var body: some View {
        NavigationView{
            ZStack {
                MainView()
                VStack {
                    Back(title: "Translate", onBackTap: {
                        self.presentationMode.wrappedValue.dismiss()
                    }, onImageTap: {})
                    ChoiceLanguage(beforeSelectedLanguage: $beforeSelectedLanguage,
                                   afterSelectedLanguage: $afterSelectedLanguage)
                    
                    InputView(beforeSelectedLanguage: $beforeSelectedLanguage,
                              afterSelectedLanguage: $afterSelectedLanguage)
                    
                    
                    Spacer()
                    
                }
            }.navigationBarHidden(true)
                .navigationBarBackButtonHidden(true)
                .navigationViewStyle(StackNavigationViewStyle())

        
        }.navigationBarHidden(true)
            .navigationBarBackButtonHidden(true)
            .navigationViewStyle(StackNavigationViewStyle())

        
    }
}

#Preview {
    TranslateView()
}

struct InputView: View {
    @State private var text: String = ""
    @State private var isTransalte = false
    @State private var dataId: Int = -1
    @Binding var beforeSelectedLanguage: String
    @Binding var afterSelectedLanguage: String
    @FocusState private var isTextEditorFocused: Bool
    
    var body: some View {
        VStack {
            ZStack(alignment: .topLeading) {
                TextEditor(text: $text)
                    .focused($isTextEditorFocused)
                    .foregroundColor(Color("input"))
                  
                    .cornerRadius(10)
                    .padding(.bottom, 20)
                    .onChange(of: text) { newValue in
//                        if newValue.hasSuffix("\n") {
//                            self.text = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
//                            isTextEditorFocused = false
//                            
//                            let requestText = "translate \(text) into \(afterSelectedLanguage) And only return the translated string without any additional characters"
//                            postRequest(with: requestText) { result in
//                                switch result {
//                                case .success(let responseString):
//                                    self.dataId = DatabaseManager.shared.insertTranslation(beforeLanguage: beforeSelectedLanguage, afterLanguage: afterSelectedLanguage, beforeText: self.text, afterText: responseString, isFavorite: false)
//                                    
//                                    print("成功",self.dataId)
//                                    if self.dataId != -1 {
//                                        self.isTransalte = true
//                                        print("jinreu")
//                                    }
//                                case .failure(let error):
//                                    print("Error: \(error)")
//                                }
//                            }
//                        }
                    }
                    .frame(maxHeight: .infinity)
                    .onTapGesture {
                        UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
                    }
                
             
                VStack {
                    Spacer()
                    HStack(spacing: 10) {
                        Image("voice")
                            .frame(width: 25)
                            .onTapGesture {
                                print("click a voice: \(text)")
                                speak(text: text, language: "zh-CN")
                            }
                        
                        Image("copy")
                            .onTapGesture {
                                writeToClipboard(text: text)
                            }
                        Spacer()
                        Button(action:{
                            isTextEditorFocused = false
                            
                            let requestText = "translate \(text) into \(afterSelectedLanguage) And only return the translated string without any additional characters"
                            postRequests(with: requestText) { result in
                                switch result {
                                case .success(let responseString):
                                    self.dataId = DatabaseManager.shared.insertTranslation(beforeLanguage: beforeSelectedLanguage, afterLanguage: afterSelectedLanguage, beforeText: self.text, afterText: responseString, isFavorite: false)
                                    
                                    
                                    print(self.dataId)
                                    
                                    // 确保 dataId 更新后才触发导航
                                    if self.dataId != -1 {
                                        self.isTransalte.toggle()
                                        print(self.isTransalte)
                                    }
                                case .failure(let error):
                                    print("Error: \(error)")
                                }
                            }
                        }) {
                            Text("translate")
                                    .foregroundColor(Color.white)
                                    .padding(.all,2)
                            }
                            .background(Color("alphaStart"))
                            .cornerRadius(5)
                        
                    } .padding()
                    
                       
                }
                    .padding(.bottom,20)
                   
             
            }
          
            NavigationLink(destination: TransResultView(id: Int64(dataId)), isActive: $isTransalte) {
                EmptyView()
            }.hidden()
          
            
          
        }
        .frame(height: 220)
        .padding()
    }
}

